package com.by.datasource.handler.mybatisPlus;

import com.by.toolkit.utils.SplitterUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Tian Wei
 * @version 1.0
 * @date 2024/3/10 12:31 PM
 */
@Slf4j
public class GroupConcatConvertListIntegerHandler extends BaseTypeHandler<List<Integer>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<Integer> contentList, JdbcType jdbcType) throws SQLException {
        //如果是空不进行设置值
        if (Objects.isNull(contentList)) {
            return;
        }
        preparedStatement.setString(i, SplitterUtil.EN_COMMA_JOINER.join(contentList));
    }

    @Override
    public List<Integer> getNullableResult(ResultSet resultSet, String s) throws SQLException {

        String content = resultSet.getString(s);
        if (Objects.isNull(content)) {
            return null;
        }
        if (StringUtils.EMPTY.equals(content)) {
            return Collections.emptyList();
        }
        return SplitterUtil.EN_COMMA_SPLITTER.omitEmptyStrings().splitToList(content).stream().map(Integer::parseInt).collect(Collectors.toList());
    }

    @Override
    public List<Integer> getNullableResult(ResultSet resultSet, int i) throws SQLException {

        String content = resultSet.getString(i);
        if (Objects.isNull(content)) {
            return null;
        }
        if (StringUtils.EMPTY.equals(content)) {
            return Collections.emptyList();
        }
        return SplitterUtil.EN_COMMA_SPLITTER.omitEmptyStrings().splitToList(content).stream().map(Integer::parseInt).collect(Collectors.toList());
    }

    @Override
    public List<Integer> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String content = callableStatement.getString(i);
        if (Objects.isNull(content)) {
            return null;
        }
        if (StringUtils.EMPTY.equals(content)) {
            return Collections.emptyList();
        }
        return SplitterUtil.EN_COMMA_SPLITTER.omitEmptyStrings().splitToList(content).stream().map(Integer::parseInt).collect(Collectors.toList());
    }
}
